package com.william.jdbcplus.boot.test.util;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: guandezhi
 * @Date: 2019/4/13 15:35
 */
public class JdbcUtils {

    private static ExecutorService threadPool = Executors.newFixedThreadPool(50);

    private static DataSource ds = DsUtil.getOracle();

    public static void executeBatch() {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = ds.getConnection();
            String sql = "insert into SYS_USER(name, mobile) values(?,?)";
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
            for (int j = 0; j < 100000; j++) {
                String mobile = "13356544556";
                Integer randNum = 0;
                Random random = new Random();
                for (int i = 0; i < 1000; i++) {
                    randNum = random.nextInt(10);
                }
                ps.setString(1, "官德志");
                ps.setString(2, mobile + String.valueOf(randNum));
                ps.addBatch();
            }
            ps.executeBatch();
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        long beginTime = System.currentTimeMillis();
        CountDownLatch latch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            threadPool.execute(() -> {
                try {
                    JdbcUtils.executeBatch();
                } catch (Exception e) {
                    System.out.println("插入数据异常");
                } finally {
                    latch.countDown();
                }
            });
        }
        latch.await();
        long endTime = System.currentTimeMillis();
        System.out.println("插入一千万数据用时：" + (endTime - beginTime) / 1000 + " 秒");
        threadPool.shutdown();
    }
}